package pdf.icepdf;

import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.util.Iterator;

public class PdfUtil {

    /**
     * 生成 PDF 的缩略图
     *
     * @param inputFile  需要生成缩略图的 PDF 的完整路径
     * @param outputFile 生成缩略图的放置路径
     */
    public static void thumbnail(String inputFile, String outputFile) throws Exception {

        FileOutputStream fos = null;
        ImageOutputStream ios = null;
        try {
            float rotation = 0f;
            // 缩略图显示倍数，1表示不缩放，0.5表示缩小到50%
            float zoom = 0.8f;

            Document document = new Document();
            document.setFile(inputFile);

            BufferedImage bufferedImage = (BufferedImage) document.getPageImage(1, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, zoom);

            Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("png");
            ImageWriter writer = iter.next();

            fos = new FileOutputStream(outputFile);
            ios = ImageIO.createImageOutputStream(fos);

            writer.setOutput(ios);
            writer.write(new IIOImage(bufferedImage, null, null));

        } catch (Exception e) {
            throw e;
        } finally {
            if (ios != null) {
                ios.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }

}
